<template>
  <el-dialog
    v-model="visible"
    title="编辑变量"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <div class="edit-variable-form">
      <!-- 字段类型 -->
      <div class="form-section">
        <div class="section-title">字段类型</div>
        <div class="field-type-buttons">
          <div
            v-for="type in fieldTypes"
            :key="type.value"
            class="field-type-btn"
            :class="{ active: formData.bllx === type.value }"
            @click="handleSwitch(type)"
          >
            <el-icon class="type-icon">
              <component :is="type.icon" />
            </el-icon>
            <span>{{ type.label }}</span>
          </div>
        </div>
      </div>

      <!-- 变量标识符 -->
      <div class="form-section">
        <el-form-item label="变量标识符" required>
          <el-input
            v-model="formData.blbsf"
            placeholder="请输入变量标识符"
            clearable
          />
        </el-form-item>
      </div>

      <!-- 变量名称 -->
      <div class="form-section">
        <el-form-item label="变量名称" required label-width="92">
          <el-input
            v-model="formData.bjbs"
            placeholder="请输入变量名称"
            clearable
          />
        </el-form-item>
      </div>

      <!-- 变量绑定 -->
      <div class="form-section">
        <div class="section-title">变量绑定</div>
        <el-radio-group v-model="formData.bindingType" @change="radioChange" class="binding-type-group">
          <el-radio label="api" v-if="formData.bllx !== '04'">API绑定</el-radio>
          <el-radio label="global" v-if="formData.bllx === '01'">全局参数绑定</el-radio>
        </el-radio-group>

        <!-- API绑定配置 -->
        <div v-if="formData.bindingType === 'api' && formData.bllx !== '04'" class="api-config">
          <div class="api-header">
            <el-select v-model="formData.apiMethod" class="method-select">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
            <el-input
              v-model="formData.apiUrl"
              placeholder="http://ip:port/xxxx"
              class="url-input"
            />
          </div>

          <!-- 参数配置 -->
          <div class="params-config">
            <el-tabs v-model="activeTab" class="params-tabs">
              <el-tab-pane label="Params" name="params">
                <div class="params-table">
                  <div class="table-header">
                    <span class="header-key">Key</span>
                    <span class="header-value">Value</span>
                    <span class="header-action">
                      <el-button
                          link
                          size="small"
                          @click="addParam"
                      >
                              <el-icon><Plus /></el-icon>
                            </el-button>
                    </span>
                  </div>
                  <div
                    v-for="(param, index) in formData.params"
                    :key="index"
                    class="table-row"
                  >
                    <el-input
                      v-model="param.key"
                      placeholder="参数名"
                      class="param-key"
                    />
                    <div class="param-value-container">
                      <el-input
                        v-model="param.value"
                        placeholder="参数值，你可输入{{}}来配置全局变量"
                        class="param-value"
                      />
                      <el-button
                        v-if="param.value.includes('{{') && param.value.includes('}}')"
                        link
                        size="small"
                        class="global-param-link"
                        @click="selectGlobalParam(index)"
                      >
                        全局参数
                      </el-button>
                    </div>
                    <div class="param-actions">
<!--                      <el-button-->
<!--                        link-->
<!--                        size="small"-->
<!--                        @click="addParam"-->
<!--                        v-if="index === formData.params.length - 1"-->
<!--                      >-->
<!--                        <el-icon><Plus /></el-icon>-->
<!--                      </el-button>-->
                      <el-button
                        link
                        size="small"
                        @click="removeParam(index)"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="Headers" name="headers">
                <div class="params-table">
                  <div class="table-header">
                    <span class="header-key">Key</span>
                    <span class="header-value">Value</span>
                    <span class="header-action">
                       <el-button
                           link
                           size="small"
                           @click="addHeader"
                       >
                              <el-icon><Plus /></el-icon>
                            </el-button>
                    </span>
                  </div>
                  <div
                    v-for="(header, index) in formData.headers"
                    :key="index"
                    class="table-row"
                  >
                    <el-input
                      v-model="header.key"
                      placeholder="Header名"
                      class="param-key"
                    />
                    <el-input
                      v-model="header.value"
                      placeholder="Header值"
                      class="param-value"
                    />
                    <div class="param-actions">
<!--                      <el-button-->
<!--                        link-->
<!--                        size="small"-->
<!--                        @click="addHeader"-->
<!--                        v-if="index === formData.headers.length - 1"-->
<!--                      >-->
<!--                        <el-icon><Plus /></el-icon>-->
<!--                      </el-button>-->
                      <el-button
                        link
                        size="small"
                        @click="removeHeader(index)"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <!-- 页面类型绑定配置 -->
        <div v-if="formData.bllx === '04'" class="api-config">
          <div style="margin: 0 0 10px 11px">Url</div>
          <div class="api-header">
            <el-input
                v-model="formData.apiUrl"
                placeholder="http://ip:port/xxxx"
                class="url-input"
            />
          </div>

          <!-- 参数配置 -->
          <div style="margin: 0 0 10px 11px">Params</div>
          <div class="params-config">
                <div class="params-table">
                  <div class="table-header">
                    <span class="header-key">Key</span>
                    <span class="header-value">Value</span>
                    <span class="header-action">
                      <el-button
                          link
                          size="small"
                          @click="addParam"
                      >
                              <el-icon><Plus /></el-icon>
                            </el-button>
                    </span>
                  </div>
                  <div
                      v-for="(param, index) in formData.params"
                      :key="index"
                      class="table-row"
                  >
                    <el-input
                        v-model="param.key"
                        placeholder="参数名"
                        class="param-key"
                    />
                    <div class="param-value-container">
                      <el-input
                          v-model="param.value"
                          placeholder="参数值"
                          class="param-value"
                      />
                      <el-button
                          v-if="param.value.includes('{{') && param.value.includes('}}')"
                          link
                          size="small"
                          class="global-param-link"
                          @click="selectGlobalParam(index)"
                      >
                        全局参数
                      </el-button>
                    </div>
                    <div class="param-actions">
<!--                      <el-button-->
<!--                          link-->
<!--                          size="small"-->
<!--                          @click="addParam"-->
<!--                          v-if="index === formData.params.length - 1"-->
<!--                      >-->
<!--                        <el-icon><Plus /></el-icon>-->
<!--                      </el-button>-->
                      <el-button
                          link
                          size="small"
                          @click="removeParam(index)"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
          </div>
        </div>

        <!-- 全局参数绑定配置 -->
        <div v-if="formData.bindingType === 'global' && formData.bllx === '01'" class="global-config">
          <div class="params-config">
            <div class="params-table">

                <el-input
                    v-model="formData.bdqjcs"
                    placeholder="请输入参数标识符"
                    class="param-key"
                />
                <el-button
                    link
                    size="small"
                    class="global-param-link"
                    @click="selectGlobalParam(index,'global')"
                >
                  全局参数
                </el-button>
              </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </div>
    </template>
    
    <!-- 全局参数选择弹窗 -->
    <GlobalParamDialog
      v-model="showGlobalParamDialog"
      :selected-param="currentSelectedParam"
      :global="editingGlobal"
      @select="handleGlobalParamSelect"
    />
  </el-dialog>
</template>

<script>
import DictApi from "@/utils/apis/dict/dict.js";
import {
  Document,
  Grid,
  Picture,
  Plus,
  Delete
} from '@element-plus/icons-vue'
import GlobalParamDialog from './GlobalParamDialog.vue'

export default {
  name: 'EditVariableDialog',
  components: {
    Document,
    Grid,
    Picture,
    Plus,
    Delete,
    GlobalParamDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    variable: {
      type: Object,
      default: () => ({})
    },
    global: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'save'],
  data() {
    return {
      visible: false,
      saving: false,
      activeTab: 'params',
      fieldTypes: [],
      globalParam: { key: '', value: '' },
      showGlobalParamDialog: false,
      currentSelectedParam: '',
      currentParamIndex: -1,
      type:'param',
      formData: {
        bllx: '',
        blbsf: '',
        bjbs: '',
        bindingType: 'api',
        apiMethod: 'GET',
        apiUrl: '',
        params: [
          { key: 'ajbh', value: '{{ajbh}}',bsfmc:'' },
        ],
        headers: [{ key: '', value: '' }],
        globalParams: [],
        bdapi:'',
        bdqjcs:'',
        xxzjbh: ''
      },
      editingGlobal: null,
    }
  },
  mounted(){
      this.getBllxDict()
  },
  watch: {
    modelValue(val) {
      this.visible = val
      if (val) {
        this.initFormData()
      }
    },
    visible(val) {
      this.$emit('update:modelValue', val)
    },
    showGlobalParamDialog(val) {
      if (!val) {
        // 全局参数弹窗关闭时重置相关状态
        this.currentParamIndex = -1
        this.currentSelectedParam = ''
      }
    }
  },
  methods: {
    initFormData() {
      // 初始化表单数据，如果有传入的变量数据则使用，否则使用默认值
      if (this.variable && Object.keys(this.variable).length > 0) {
        this.formData = {
          bllx: this.variable.bllx || '01',
          blbsf: this.variable.text || '',
          bjbs: this.variable.bjbs || this.variable.label || '',
          bindingType: this.variable.bindingType || 'api',
          apiMethod: this.variable.apiMethod || 'GET',
          apiUrl: this.variable.apiUrl || '',
          params: this.variable.params || [{ key: '', value: '' ,bsfmc:''}],
          headers: this.variable.headers || [{ key: '', value: '' }],
          globalParams: this.variable.globalParams || [],
          bdqjcs: this.variable.bdqjcs || '',
          xxzjbh: this.variable.xxzjbh || '',
        }
      } else {
        // 重置为默认值
        this.formData = {
          bllx: '',
          blbsf: '',
          bjbs: '',
          bindingType: 'api',
          apiMethod: 'GET',
          apiUrl: '',
          params: [{ key: '', value: '' ,bsfmc:''}],
          headers: [{ key: '', value: '' }],
          globalParams: [{ csbsf: '', csmc: ''}],
          bdqjcs:'',
          xxzjbh:''
        }
      }
      this.formData.globalParams = this.global
    },
    addParam() {
      this.formData.params.push({ key: '', value: '',bsfmc:'' })
    },
    removeParam(index) {
      this.formData.params.splice(index, 1)
    },
    addHeader() {
      this.formData.headers.push({ key: '', value: '' })
    },
    removeHeader(index) {
      this.formData.headers.splice(index, 1)
    },
    selectGlobalParam(paramIndex,type='param' ) {
      this.type=type;
      if  (type=='param'){
        this.currentParamIndex = paramIndex
        this.currentSelectedParam = this.formData.params[paramIndex].value.replace(/[{}]/g, '')
      }
      if (this.formData.globalParams.length > 0){
        this.editingGlobal = this.formData.globalParams
      }
      // 确保弹窗能正确显示
      this.$nextTick(() => {
        this.showGlobalParamDialog = true
      })
    },
    
    handleGlobalParamSelect(selectedParams) {
      const selectedParam = selectedParams.param[0]
      if(this.type=='param'){
        if (selectedParams && selectedParams.param.length > 0) {
          // 使用第一个选中的参数
          if (this.currentParamIndex >= 0) {
            this.formData.params[this.currentParamIndex].value = `{{${selectedParam.csbsf}}}`
            this.formData.params[this.currentParamIndex].bsfmc = `${selectedParam.csmc}`
          }
        }
      }else{
        this.formData.bdqjcs=`${selectedParam.csbsf}`;
      }
      this.formData.globalParams = selectedParams.globalParam
    },
    //变量类型切换
    handleSwitch(data){
      if (data.value === '02' || data.value === '03'){
        this.formData.bindingType = 'api'
      }
      this.formData.bllx = data.value
      this.formData.bdqjcs = ''
    },
    radioChange(obj){
      if (obj === 'api'){
        this.formData.bdqjcs = ''
      }else if (obj === 'global'){
        this.formData.apiUrl = ''
        this.formData.params= [{ key: '', value: '' ,bsfmc:''}]
        this.formData.headers= [{ key: '', value: '' }]
      }
    },
    handleClose() {
      this.visible = false
    },
    async handleSave() {
      // 表单验证
      if (!this.formData.blbsf?.trim()) {
        this.$message.error('请输入变量标识符');
        return;
      }
      if (!this.formData.bjbs?.trim()) {
        this.$message.error('请输入变量名称');
        return;
      }
      if (this.formData.bindingType === 'api') {
        const url = this.formData.apiUrl?.trim();
        if (!url) {
          this.$message.error('请输入API地址');
          return;
        }
        if (!url.startsWith('http://')) {
          this.$message.error('API地址必须以 http:// 开头');
          return;
        }
      }

      this.saving = true
      try {
        if (this.formData.bllx !== '04'){
          let apiParams = JSON.stringify({
            method:this.formData.apiMethod,
            url:this.formData.apiUrl,
            params:this.formData.params,
            headers:this.formData.headers
          })
          this.formData.bdapi = apiParams
        }else if (this.formData.bindingType === 'global' && this.formData.bllx === '01'){
          this.$emit('save', this.formData)
        }else {
          let apiParams = JSON.stringify({
            url:this.formData.apiUrl,
            params:this.formData.params
          })
          this.formData.bdapi = apiParams
        }
        this.$emit('save', this.formData)
        this.visible = false
      } catch (error) {
        this.$message.error('保存失败，请重试')
      } finally {
        this.saving = false
      }
    },
    getBllxDict(){
      DictApi.getzdmByzdlb({zdlbdm: 'ZDY_BLLX'}).then(res => {
        if (res.code === '0') {
          let dataList = res.data
          this.fieldTypes = dataList.map(item => {
            if (item.label === '文本'){
              return {
                label: item.label,
                value: item.value,
                icon: 'Document'
              };
            }
            if (item.label === '表格'){
              return {
                label: item.label,
                value: item.value,
                icon: 'Grid'
              };
            }
            if (item.label === '图片'){
              return {
                label: item.label,
                value: item.value,
                icon: 'Picture'
              };
            }
            if (item.label === '页面'){
              return {
                label: item.label,
                value: item.value,
                icon: 'Document'
              };
            }
          });
        }
      })
    },
  }
}
</script>

<style scoped>
.edit-variable-form {
  padding: 0 20px;
}

.form-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #2B2B2B;
  margin-bottom: 12px;
}

.field-type-buttons {
  display: flex;
  gap: 12px;
}

.field-type-btn {
  flex: 1;
  height: 60px;
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.field-type-btn:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.field-type-btn.active {
  border-color: #409EFF;
  background: #F0F9FF;
  color: #409EFF;
}

.type-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.field-type-btn span {
  font-size: 12px;
}

.binding-type-group {
  margin-bottom: 16px;
}

.api-config {
  border: 1px solid #EBEEF5;
  border-radius: 6px;
  padding: 16px;
  background: #FAFAFA;
}

.api-header {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.method-select {
  width: 100px;
}

.url-input {
  flex: 1;
}

.params-config {
  background: white;
  border-radius: 4px;
}

.params-tabs {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.params-table {
  padding: 16px;
}

.table-header {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #EBEEF5;
  font-weight: 500;
  color: #606266;
}

.header-key {
  width: 40%;
  padding-right: 8px;
}

.header-value {
  width: 40%;
  padding-right: 4px;
}

.header-action {
  width: 20%;
  text-align: center;
}

.table-row {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #F5F7FA;
}

.table-row:last-child {
  border-bottom: none;
}

.param-key {
  width: 40%;
  padding-right: 8px;
}

.param-value-container {
  width: 40%;
  padding-right: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.param-value {
  flex: 1;
}

.global-param-link {
  color: #409EFF;
  font-size: 12px;
  padding: 0;
  min-width: auto;
}

.param-actions {
  width: 20%;
  display: flex;
  justify-content: center;
  gap: 4px;
}

.global-config {
  padding: 16px;
  border: 1px solid #EBEEF5;
  border-radius: 6px;
  /*background: #FAFAFA;*/
  display: flex;
  flex-direction: column;
}

.form-item-container {
  display: flex;
  flex-direction: row;
  align-items: center; /* 垂直居中对齐 */
}

.form-item-container .el-form-item {
  margin-right: 20px; /* 输入框之间的间距 */
}

.form-item-container .el-form-item:last-child {
  margin-right: 0; /* 最后一个输入框不需要右边距 */
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2B2B2B;
}

:deep(.el-tabs__header) {
  margin: 0;
  background: #F5F7FA;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 16px;
}

:deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
}

:deep(.el-tabs__content) {
  padding: 0;
}
</style>
